/*
 * @(#)DynamicSqlUtils.java
 * 2016年10月22日 下午10:54:00
 * 
 * Copyright (c) 2016 QiYunInfoTech - All Rights Reserved.
 * ====================================================================
 * The QiYunInfoTech License, Version 1.0
 *
 * This software is the confidential and proprietary information of QiYunInfoTech.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with QiYunInfoTech.
 */
package com.qyxx.platform.common.utils;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 *  动态sql解析
 *  @author bobgao
 *  @version 1.0 2018年08月28日 下午21:27:00
 *  @since jdk1.6 
 */

public class DynamicSqlUtils {
	
	private static final Configuration cfg = new Configuration(); 
	
	/**
	 * freemarker解析动态sql模板
	 * 
	 * @param sqlTemplate
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String parseSqlByFreeMarker(String sqlTemplate, Map<String, Object> params) {
		StringWriter writer = new StringWriter();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("sqlTemplate", sqlTemplate);
        cfg.setTemplateLoader(stringLoader);
        try {
        	Template template = cfg.getTemplate("sqlTemplate","utf-8");
            template.process(params, writer);
            return writer.toString();
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return sqlTemplate;
	}
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String testSql = "select a.DanHao, t.ChanPinBianHao, t.KeHuHuoHao, t.ChanPinMingChen, t.ChanPinGuiGe, t.DanWei, "
						+ "	t.DanJia, t.ShuLiang, t.ZongJia, t.GongZuoZhongXin, a.KeHuHeTongHao, t.ID "
						+ " from WAI_XIAO_HE_TONG_ZI_BIAO1 t LEFT JOIN WAI_XIAO_HE_TONG_ZHU_BIAO a ON t.MASTER_ID = a.ID "
						+ " where t.ChanPinZhuangTai IN('35','48') AND t.MASTER_ID in (:ids)"
						+ " \n<#if aa == '11' && bb == '22'> AND t.ID = ${aa}</#if>\n";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("aa", "11");
		params.put("bb", "222");
		String bs = parseSqlByFreeMarker(testSql, params);
		System.out.println(bs);
	}

}
